<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="js/vue.js"></script>
</head>
<body>
<div id="appId">


    <input type="text"  v-model="inputData"/>
    <button @click="sendMsg">发送</button>
    <br>
    <button @click="exit">退出</button>
    <ul>
        <li v-for="c in chatRecord" v-text="c"></li>
    </ul>
</div>
<script>
    new Vue({
        el: '#appId',
        data() {
            return {
                webSocket: null,
                inputData: null,
                chatRecord: []
            }
        },
        created() {
            this.initWebSocket();

        },
        methods: {

            initWebSocket() {
                this.webSocket = new WebSocket("ws://localhost:28888/messages")
                this.webSocket.onopen = (event) => {
                    console.log('webSocket已打开')
                }

                this.webSocket.onmessage = (event) => {
                    console.log('接收到来自服务端的消息：', event.data)
                    this.chatRecord.push(JSON.parse(event.data))
                }

                this.webSocket.onclose = (event) => {

                    console.log("服务器已断开："+event)
                }
            },
            sendMsg() {
                this.webSocket.send(this.inputData)
                this.inputData = null
            },
            exit() {
                this.webSocket.close(998, "不玩了")
            }

        }
    })
</script>
</body>
</html>